const Koa = require('koa');

const app = new Koa();

const path = require('path');

//处理静态资源  koa-static 
const static = require('koa-static');

const router = require('koa-router')();

const query = require('./db/index');

const bodyparser = require('koa-bodyparser');

//挂载处理静态资源的中间件
app.use(static(path.join(__dirname,'./public')));

//注：一定放在路由挂载中间上
app.use(bodyparser());

//挂载路由中间件
app.use(router.routes());

app.use(router.allowedMethods());

//获取列表
router.get('/api/list',async (ctx,next) => {
    //每页的条数  limit  当前页码  pagenum  
    let {limit=2,pagenum=1,sex} = ctx.query;

    /**
     * 1    0 
     * 
     * 2    2
     * 
     * 3    4
     * 
     * 
    */

    //起始下标
    let startIndex = (pagenum-1)*limit;
    //获取数据
    let list = await query(`select * from userlist where sex=? limit ${startIndex},${limit}`,[sex]);

    //查询总条数
    let total = await query('select count(*) from userlist where sex=?',[sex]);

    ctx.body = {
        code:1,
        data:list,
        total:total[0]['count(*)']
    }
})

//添加数据
router.post('/api/add',async (ctx) => {
    //获取前端传递的参数
    console.log(ctx.request.body);
    let {username,phone} = ctx.request.body;
    //容错处理
    if(username && phone){
        try{    
            await query('insert into userlist (username,phone) values (?,?)',[username,phone]);
            ctx.body = {
                code:1,
                msg:'添加成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }
    }else{
        ctx.body = {
            code:2,
            msg:'参数有误'
        }
    }
})

//删除数据
router.delete('/api/del',async (ctx) => {
    let {id} = ctx.query;
    if(id){
        try{
            await query('delete from userlist where id=?',[id]);
            ctx.body = {
                code:1,
                msg:'删除成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }
    }else{
        ctx.body = {
            code:2,
            msg:'参数有误'
        }
    }  
})

//更新
router.put('/api/update',async (ctx) => {
    //id  username phone
    let {id,username,phone} = ctx.request.body;
    //容错处理
    if(id && username && phone){
        try{
            await query('update userlist set username=?,phone=? where id=?',[username,phone,id]);
            ctx.body = {
                code:1,
                msg:'更新成功'
            }
        }catch(e){
            ctx.body = {
                code:0,
                msg:e
            }
        }
    }else{
        ctx.body = {
            code:2,
            msg:'参数传递有误'
        }
    }

})

app.listen(3000,() => {
    console.log("服务启动成功")
})
